<template>
	<el-dialog v-model="dialogVisible" append-to-body :show-close="false" :close-on-click-modal="false"
		class="flex-align" style="width: 100%;height: 100%;padding: 30px 24px;margin: 0;background: transparent;">
		<template #header>
			<el-card style="width: 100%;height: 100%;" body-style="padding: 0;" shadow="never">
				<template #header>
					<div class="flex-space-between">
						<div>
							<el-text style="font-size: 16px;">
								进项发票
							</el-text>
						</div>
						<div>
							<el-button @click="closeDialog">取消</el-button>
							<!-- <el-button @click="closeDialog">
								保存并继续创建
								<el-icon style="margin-left: 4px;">
									<ArrowDown />
								</el-icon>
							</el-button> -->
							<el-button type="primary" @click="submitForm(vFormRef)">
								保存
							</el-button>
						</div>
					</div>
				</template>
				<el-scrollbar ref="scrollbarRef" @scroll="handleScroll"
					:style="`height: calc(100vh - 69px - ( 30px + 30px));`">
					<el-form :model="formData" :rules="rules" ref="vFormRef" label-position="top" label-width="50px"
						style="padding: 16px;">
						<el-form-item label="发票状态" prop="invoiceStatusId">
							<el-input v-model="formData.invoiceStatusId " readonly type="text" clearable class="my">
								<template #prefix>
									<div>
										<el-check-tag
											:style="`color: ${invoiceStatusIndex===key?'#fff':''};${invoiceStatusIndex===key?`background: ${item.bg}`:''}`"
											v-for="(item,key) in invoiceStatusTags" :key="key"
											:checked="invoiceStatusIndex===key"
											@change="tagChange(key,'invoiceStatusId')">{{item.text}}</el-check-tag>
									</div>
								</template>
							</el-input>
						</el-form-item>
						<el-form-item label="供应商" prop="supplier">
							<el-select @clear="selectClear('supplier')" v-model="formData.supplier"
								@change="(value:any)=>selectChange(value,'supplier')" multiple ref="supplier" clearable>
								<el-option v-for="item in supplierOption" :key="key" :label="item?.label"
									:value="item?.value">
									<!--  -->
									<div class="flex-align-center">
										<el-icon :color="item?.color">
											<component :is="item?.icon"></component>
										</el-icon>
										<!--  -->
										<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
									</div>
								</el-option>
								<!--  -->
								<template #tag>
									<div style="padding-left: 6px;">
										<div>
											<div class="flex-align-center">
												<el-icon :color="supplierOption[supplierIndex]?.color">
													<component :is="supplierOption[supplierIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{supplierOption[supplierIndex]?.label}}</el-text>
											</div>
										</div>
									</div>
								</template>
							</el-select>
						</el-form-item>
						<el-form-item label="采购订单" prop="purchaseOrder">
							<el-select @clear="selectClear('purchaseOrder')" v-model="formData.purchaseOrder"
								@change="(value:any)=>selectChange(value,'purchaseOrder')" multiple ref="purchaseOrder"
								clearable>
								<el-option v-for="item in purchaseOrderOption" :key="key" :label="item?.label"
									:value="item?.value">
									<!--  -->
									<div class="flex-align-center">
										<el-icon :color="item?.color">
											<component :is="item?.icon"></component>
										</el-icon>
										<!--  -->
										<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
									</div>
								</el-option>
								<!--  -->
								<template #tag>
									<div style="padding-left: 6px;">
										<div>
											<div class="flex-align-center">
												<el-icon :color="purchaseOrderOption[purchaseOrderIndex]?.color">
													<component :is="purchaseOrderOption[purchaseOrderIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{purchaseOrderOption[purchaseOrderIndex]?.label}}</el-text>
											</div>
										</div>
									</div>
								</template>
							</el-select>
						</el-form-item>
						<el-form-item label="发票金额" prop="invoiceAmount">
							<el-input placeholder="请填写" type="number" v-model="formData.invoiceAmount" clearable></el-input>
						</el-form-item>
						<el-form-item label="发票附件" prop="invoiceAttachment">
							<el-input type="text" readonly clearable>
								<template #prefix>
									<el-upload v-model:file-list="formData.files" action="/api/oss/policy"
										:on-success="onSuccess" :headers="{'Authorization':cookie.get('token')}"
										:limit="1">
										<el-button v-if="!formData.invoiceAttachment" text :icon="UploadFilled">
											上传图片
										</el-button>
										<el-image v-else preview-teleported
											style="width: 30px; height: 30px;margin: 10px auto;"
											:src="formData.invoiceAttachment"
											:preview-src-list="[formData.invoiceAttachment]" />
									</el-upload>
								</template>
							</el-input>
						</el-form-item>
						<el-form-item label="发票类型" prop="invoiceTypeId">
							<el-input v-model="formData.invoiceTypeId" readonly type="text" clearable class="my">
								<template #prefix>
									<div>
										<el-check-tag
											:style="`color: ${invoiceTypeIndex===key?'#fff':''};${invoiceTypeIndex===key?`background: ${item.bg}`:''}`"
											v-for="(item,key) in invoiceTypeTags" :key="key"
											:checked="invoiceTypeIndex===key"
											@change="tagChange(key,'invoiceTypeId')">{{item.text}}</el-check-tag>
									</div>
								</template>
							</el-input>
						</el-form-item>
						<el-form-item label="开票日期" prop="billingDate">
							<el-date-picker placeholder="请选择" v-model="formData.billingDate" style="width:100%;" type="date" />
						</el-form-item>
						<el-form-item label="录入人员" prop="entryClerk">
							<el-input placeholder="请填写" type="text" v-model="formData.entryClerk" clearable></el-input>
						</el-form-item>
					</el-form>
				</el-scrollbar>
				<!--  -->
			</el-card>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { useRoute, useRouter } from 'vue-router';
	import request from '../../../utils/request';
	import {UploadFilled, UserFilled, WalletFilled, CirclePlus, DocumentAdd, Delete } from '@element-plus/icons-vue';
	import { mergeObjects, formatNumber } from '../../../utils';
	import { useSelect } from '../../../utils/mixins';
	import { ElMessage, FormInstance } from 'element-plus';
	import { getShipments } from '../../../api/shipmentAPI';
	import { jwtDecode } from 'jwt-decode';
	import cookie from 'js-cookie';
	const emits = defineEmits(['update']);
	const { handSelectChange } = useSelect();
	const router = useRouter();
	const route = useRoute();
	const vFormRef = ref(null);
	const loading = ref(false);

	// 表单
	const formData = ref({
		invoiceStatusId: null,//发票状态
		supplierId: null,//供应商
		supplier: [],
		purchaseOrderId: null,//采购订单
		purchaseOrder: [],
		invoiceAmount: null,//发票金额
		invoiceAttachment: null,//发票附件
		files:[],
		invoiceTypeId: null,//发票类型
		billingDate: null,//开票日期
		entryClerk: null,//录入人员
	});
	//验证
	const rules = reactive({
		invoiceStatusId: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//发票状态
		supplier: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//供应商
		purchaseOrder: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//采购订单
		invoiceAmount: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//发票金额
		invoiceAttachment: null,//发票附件
		invoiceTypeId: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//发票类型
		billingDate: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//开票日期
		entryClerk: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//录入人员
	});
	const pageData = ref({
		pageNum: 1,
		pageSize: 1000,
		total: 0,
		pages: 0,
	});
	//发票状态
	const invoiceStatusTags = ref([]);
	const invoiceStatusIndex = ref(-1);
	//供应商
	const supplierOption = ref([]);
	const supplierIndex = ref(-1);
	const supplier = ref(null);
	//采购订单
	const purchaseOrderOption = ref([]);
	const purchaseOrderIndex = ref(-1);
	const purchaseOrder = ref(null);
	//发票类型
	const invoiceTypeTags = ref([]);
	const invoiceTypeIndex = ref(-1);
	//
	const dialogVisible = ref(false);
	/**
	 * 打开弹出层
	 */
	const openDialog = () => {
		dialogVisible.value = true;
		setTimeout(async () => {
			const result = await getPageId();
			//
			if (result) {
				getInvoiceStatusList();
				getSupplierList();
				getInvoiceTypeList();
				if(!route.query.id){
					invoiceStatusIndex.value = 0;
					formData.value.invoiceStatusId = 186;
				}
			}
		}, 10);
	}
	/**
	 * 关闭弹出层
	 */
	const closeDialog = () => {
		dialogVisible.value = false;
		vFormRef.value.resetFields();
		//清空url参数
		router.push({ query: {} });
	}
	//获取当前页面的数据
	const getPageId = async () => {
		if (!route.query.id) {
			const token = cookie.get('token');
			const decodedToken : {
				username : string
			} = jwtDecode(token);
			// console.log('decodedToken--->', decodedToken);
			//
			formData.value.entryClerk = decodedToken?.username;
			//
			return true;
		}
		//
		const result = await request({
			url: '/SalesReceipt/InputInvoiceById',
			params: {
				id: route.query.id
			},
		});
		//
		console.log('getPageId --->', result);
		//
		formData.value = { ...result.data.t };
		//
		return true;
	}
	//改变
	const selectChange = (value : Array<any>, type : string, key : number) => {
		//所有下拉框的配置列表
		const typeList = [{
			type: 'supplier', //哪一个下拉框，根据ref
			option: supplierOption, //下拉列表选项
			indexVar: supplierIndex, //当前选中项
			idVar: 'supplierId', //当前id值
			blurRef: supplier, //ref
			fun: getPurchaseOrderById
		}, {
			type: 'purchaseOrder', //哪一个下拉框，根据ref
			option: purchaseOrderOption, //下拉列表选项
			indexVar: purchaseOrderIndex, //当前选中项
			idVar: 'purchaseOrderId', //当前id值
			blurRef: purchaseOrder, //ref
		},];
		//
		handSelectChange(formData, typeList, value, type, key);
	}
	//tag改变
	const tagChange = (index : number, type : string) => {
		// if (type === 'invoiceStatusId') {
		// 	if (invoiceStatusIndex.value === index) {
		// 		formData.value[type] = 0;
		// 		invoiceStatusIndex.value = -1;
		// 		return;
		// 	}
		// 	invoiceStatusIndex.value = index;
		// 	formData.value[type] = invoiceStatusTags.value[index].value;
		// }
		if (type === 'invoiceTypeId') {
			if (invoiceTypeIndex.value === index) {
				formData.value[type] = 0;
				invoiceTypeIndex.value = -1;
				return;
			}
			invoiceTypeIndex.value = index;
			formData.value[type] = invoiceTypeTags.value[index].value;
		}
	}
	//获取发票状态
	const getInvoiceStatusList = async () => {
		const data = await getShipments('invoice_status', 'tag');
		invoiceStatusTags.value = [];
		data.forEach((item : any, key : number) => {
			invoiceStatusTags.value.push(item);
			//
			if (formData.value.invoiceStatusId === item.value) {
				invoiceStatusIndex.value = key;
			}
		});
	}
	//获取供应商
	const getSupplierList = async () => {
		const result = await request({
			url: '/SalesReceipt/selectProcuredSupplier',
		});
		console.log('getSupplierList --->', result);
		supplierOption.value = [];
		result.data.t.forEach((item : any, key : number) => {
			supplierOption.value.push({
				label: `${item.supplierShortName}`,
				value: item.supplierId,
				icon: UserFilled,
				color: '#82b51b'
			});
			if (formData.value.supplierId === item.supplierId) {
				formData.value.supplier = [item.supplierId];
				supplierIndex.value = key;
				getPurchaseOrderById(item.supplierId);
			}
		});
	}
	//根据id获取采购订单
	const getPurchaseOrderById = async (supplierId : number) => {
		const result = await request({
			url: '/SalesReceipt/selectGOrder',
			params: { supplierId }
		});
		console.log('getPurchaseOrderById --->', result);
		purchaseOrderOption.value = [];
		result.data.t.forEach((item : any, key : number) => {
			purchaseOrderOption.value.push({
				label: `${item.purchaseOrderNumber}_${formatNumber(item.totalAmount, '元')}`,
				value: item.purchaseOrderId,
				icon: UserFilled,
				color: '#82b51b'
			});
			if (formData.value.purchaseOrderId === item.purchaseOrderId) {
				formData.value.purchaseOrder = [item.purchaseOrderId];
				purchaseOrderIndex.value = key;
			}
		});
	}
	//获取发票类型
	const getInvoiceTypeList = async () => {
		const data = await getShipments('invoice_type ', 'tag');
		invoiceTypeTags.value = [];
		data.forEach((item : any, key : number) => {
			invoiceTypeTags.value.push(item);
			//
			if (formData.value.invoiceTypeId === item.value) {
				invoiceTypeIndex.value = key;
			}
		});
	}
	//提交表单
	const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				console.log('submitForm ---> ', formData.value);
				const data = { ...formData.value };
				delete data.supplier;
				delete data.purchaseOrder;
				let type = '';
				if (!route.query.id) {
					type = '/saveInputInvoice';
				} else {
					type = '/updateInputInvoice';
				}
				//
				const result = await request({
					url: '/SalesReceipt' + type,
					data: data,
					method: 'post'
				});
				//
				console.log('submitForm--->', result);
				//

				if (result.data.code === 200) {
					ElMessage.success({
						message: '操作成功！'
					});
				} else {
					ElMessage.error({
						message: result.data.msg
					});
				}
				//
				setTimeout(() => {
					closeDialog();
					emits('update');
				}, 1);
			} else {
				//
				console.log('error submit!', fields);
			}
		});
	}
	//凭证上传成功
	const onSuccess = (res : any) => {
		console.log('onSuccess --->', res);
		//
		formData.value.invoiceAttachment = res.t;
	}
	defineExpose({
		openDialog
	});
</script>
<style>
	@import '../../../assets/css/my-form-item.css';

	.form-item-bg {
		background-color: #bfdfff;
	}

	.form-item-bg1 {
		background-color: #a5f2e5;
	}

	.my.el-input .el-input__inner {
		opacity: 0;
	}

	/*  */
	.avatar-uploader {
		width: 178px;
		height: 178px;
	}

	.avatar-uploader .avatar {
		width: 100%;
		height: 100%;
	}

	.avatar-uploader .el-upload {
		width: 100%;
		height: 100%;
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

	.el-scrollbar__view {
		display: block !important;
	}

	/*  */
</style>

<style scoped lang="scss">
	@import '../../../assets/css/index.scss';
</style>